package com.snap.vseries.manager;

import android.os.Environment;
import android.support.annotation.NonNull;

import com.snap.vseries.AppConfig;
import com.snap.vseries.bean.SettingInfo;
import com.snap.vseries.threadmanager.ThreadListener;
import com.snap.vseries.threadmanager.ThreadManger;
import com.snap.vseries.utils.FileUtils;

import java.io.File;


public class ConfigManager {
    private static ConfigManager sInstance = new ConfigManager();
    private SettingInfo mInfo;
    private String path;

    private ConfigManager() {
    }

    public static ConfigManager getInstance() {
        return sInstance;
    }

    /**
     * 初始化 配置路径 异步加载配置到内存中
     */
    public void init() {
        loadConfig();
    }

    /**
     * 设置页面 调用此处获取 配置的各项值
     * 通常：对这个对象调用setter方法后，紧跟着调用{@link #update()}
     */
    @NonNull
    public SettingInfo getSettingInfo() {
        if (mInfo == null) {
            loadConfig();
        }
        return mInfo;
    }

    /**
     * 外部调用这个方法来更新文件
     */
    public void update() {
        ThreadManger.get().add(new ThreadListener() {
            @Override
            public void doAction() throws Exception {
                saveConfig();
            }
        });
    }

    private void loadConfig() {
        path = Environment.getExternalStorageDirectory().getPath()
                + AppConfig.ROOT_DIRECTORY + "sys.config";
        File file = new File(path);
        if (file.exists()) {
            byte[] byteArray = FileUtils.readFile(file);
            if (byteArray != null) {
                mInfo = FileUtils.deserialize(byteArray, SettingInfo.class);
            }
        }

        if (mInfo == null) {
            mInfo = SettingInfo.generateDefault();
            saveConfig();
        }
    }

    /**
     * 存储config文件
     */
    private void saveConfig() {
        byte[] byteArray = FileUtils.serialize(mInfo);
        File file = new File(path);
        FileUtils.writeFile(file, byteArray);
    }
}